from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify
import markdown

class Category(models.Model):
    """文章分类模型"""
    name = models.CharField(max_length=100, verbose_name='分类名称')
    slug = models.SlugField(max_length=100, unique=True, verbose_name='URL别名')
    description = models.TextField(blank=True, verbose_name='分类描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '分类'
        verbose_name_plural = '分类'
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse('blog:category_detail', kwargs={'slug': self.slug})

class Tag(models.Model):
    """文章标签模型"""
    name = models.CharField(max_length=50, unique=True, verbose_name='标签名称')
    slug = models.SlugField(max_length=50, unique=True, verbose_name='URL别名')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '标签'
        verbose_name_plural = '标签'
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

class Article(models.Model):
    """文章模型"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
    ]
    
    title = models.CharField(max_length=200, verbose_name='标题')
    slug = models.SlugField(max_length=200, unique=True, verbose_name='URL别名')
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='作者')
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='分类')
    tags = models.ManyToManyField(Tag, blank=True, verbose_name='标签')
    excerpt = models.TextField(max_length=500, blank=True, verbose_name='摘要')
    content = models.TextField(blank=True, verbose_name='内容')
    featured_image = models.ImageField(upload_to='articles/', blank=True, null=True, verbose_name='特色图片')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft', verbose_name='状态')
    is_featured = models.BooleanField(default=False, verbose_name='是否推荐')
    views = models.PositiveIntegerField(default=0, verbose_name='浏览次数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '文章'
        verbose_name_plural = '文章'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        if not self.slug:
            # 生成slug，处理特殊字符和长度限制
            import re
            # 先清理标题中的特殊字符
            clean_title = re.sub(r'[^\w\s-]', '', self.title)
            # 限制长度并生成slug
            truncated_title = clean_title[:100]  # 限制在100字符内
            self.slug = slugify(truncated_title)
            
            # 如果slug为空或太短，使用ID作为后缀
            if not self.slug or len(self.slug) < 3:
                self.slug = f"article-{self.id or 'new'}"
            
            # 确保slug唯一性
            original_slug = self.slug
            counter = 1
            while Article.objects.filter(slug=self.slug).exclude(id=self.id).exists():
                self.slug = f"{original_slug}-{counter}"
                counter += 1
                
        if not self.excerpt and self.content:
            # 自动生成摘要
            plain_text = markdown.markdown(self.content, extensions=['markdown.extensions.extra'])
            self.excerpt = plain_text[:200] + '...' if len(plain_text) > 200 else plain_text
        super().save(*args, **kwargs)
    
    def get_absolute_url(self):
        return reverse('blog:article_detail', kwargs={'slug': self.slug})
    
    def get_markdown_content(self):
        """将Markdown内容转换为HTML"""
        return markdown.markdown(
            self.content,
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
            ]
        )
    
    def increment_views(self):
        """增加浏览次数"""
        self.views += 1
        self.save(update_fields=['views'])

class Comment(models.Model):
    """评论模型"""
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', verbose_name='文章')
    name = models.CharField(max_length=100, verbose_name='姓名')
    email = models.EmailField(verbose_name='邮箱')
    website = models.URLField(blank=True, verbose_name='网站')
    content = models.TextField(verbose_name='评论内容')
    is_approved = models.BooleanField(default=False, verbose_name='是否审核通过')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '评论'
        verbose_name_plural = '评论'
        ordering = ['-created_at']
    
    def __str__(self):
        return f'{self.name} 对 "{self.article.title}" 的评论'
